Introduction to Open Data Science - Course Project

About the project

Write a short description about the course and add a link to your GitHub repository here. This is an R Markdown (.Rmd) file so you should use R Markdown syntax.

# This is a so-called "R chunk" where you can write R code.

date()
## [1] "Fri Dec 10 12:44:22 2021"

I heard from my colleague about the Introduction to Open Data Science. She warmly recommended the course which is why I signed up for autumn term 2021.

I am looking forward to learning more about open data science and best practice for data analysis in order to make my work easily accessible and readable for my colleagues.


Week 2: Regression and model validation

Describe the work you have done this week and summarize your learning.

date()
## [1] "Fri Dec 10 12:44:22 2021"

1) Introduction to and exploration of the data

The data used for this exercise is derived from a study exploring the relationship between learning approaches and student’s achievements in an introductory statistics course in Finland conducted during years 2014 and 2015. Students in an introductory statistics course filled in a questionnaire exploring their learning approaches and study skills. The student’s achievements on the course were measured by the points they received in the exams. Only a part of the original data will be used in this exercise and is explored below. This smaller data set is in a data frame called learning2014.

# import the data 
learning2014 <- read.table("./Data/learning2014.txt", sep = "\t")

# structure of the data frame
str(learning2014) 
## 'data.frame':    166 obs. of  7 variables:
##  $ gender  : chr  "F" "M" "F" "M" ...
##  $ age     : int  53 55 49 53 49 38 50 37 37 42 ...
##  $ attitude: num  3.7 3.1 2.5 3.5 3.7 3.8 3.5 2.9 3.8 2.1 ...
##  $ deep    : num  3.58 2.92 3.5 3.5 3.67 ...
##  $ stra    : num  3.38 2.75 3.62 3.12 3.62 ...
##  $ surf    : num  2.58 3.17 2.25 2.25 2.83 ...
##  $ points  : int  25 12 24 10 22 21 21 31 24 26 ...
colSums(is.na(learning2014)) # number of missing values in the data
##   gender      age attitude     deep     stra     surf   points 
##        0        0        0        0        0        0        0

There are 166 observations by 7 variables and no missing data in the data set.

Variables age and gender are self-explanatory, but the other 5 variables are explained below:

  • attitude: student’s attitude towards statistics
  • surf: surface approach for learning — memorizing without understanding (lack of purpose, unrelated memorizing)
  • deep: deep approach for learning — intention to maximize understanding (relating ideas, use of evidence)
  • stra: strategic approach for learning — maximizing the chance of achieving the highest possible grades (organized studying and time management)
  • points: points received in the exams of the course (measure of student’s achievements)

Explanations for the variables are derived from here.

Graphical overview of the data

# first upload the libraries
library(ggplot2)
library(GGally)
## Registered S3 method overwritten by 'GGally':
##   method from   
##   +.gg   ggplot2
# now the graph
ggpairs(learning2014, mapping = aes(col = gender, alpha = 0.5), 
        lower = list(combo = wrap("facethist", bins = 20)))

# summaries of the variables in the data
summary(learning2014)
##     gender               age           attitude          deep      
##  Length:166         Min.   :17.00   Min.   :1.400   Min.   :1.583  
##  Class :character   1st Qu.:21.00   1st Qu.:2.600   1st Qu.:3.333  
##  Mode  :character   Median :22.00   Median :3.200   Median :3.667  
##                     Mean   :25.51   Mean   :3.143   Mean   :3.680  
##                     3rd Qu.:27.00   3rd Qu.:3.700   3rd Qu.:4.083  
##                     Max.   :55.00   Max.   :5.000   Max.   :4.917  
##       stra            surf           points     
##  Min.   :1.250   Min.   :1.583   Min.   : 7.00  
##  1st Qu.:2.625   1st Qu.:2.417   1st Qu.:19.00  
##  Median :3.188   Median :2.833   Median :23.00  
##  Mean   :3.121   Mean   :2.787   Mean   :22.72  
##  3rd Qu.:3.625   3rd Qu.:3.167   3rd Qu.:27.75  
##  Max.   :5.000   Max.   :4.333   Max.   :33.00

The number of females is almost twice the number of males in the data, but there seems to be no significant difference between the females and males, except a slightly lower values in attitude seen in females compared to males (see the box plots on the top panel in the paired plot). However, this might be due to the lower number of male participants in the data. The age is between 17 – 55, but most of the participants fall below age 30. The rest of the variables (attitude, deep, stra, surf, points) seem to be close to normal distribution. Variables points and attitude correlate positively, while there is slight negative correlation between deep and surf. This negative correlation is only seen in the male participants.

2) Regression model

We will use regression analysis to see if we could build a model to predict points from the other variables. The dependent variable (response variable) here is points and we will choose three possible explanatory variables to start building the model. The three explanatory variables will be attitude, stra and deep.

# We will start building the model using three explanatory variables
M1 <- lm(points ~ 1 + attitude + stra + deep, data = learning2014)
# Show a summary of the fitted model
summary(M1)
## 
## Call:
## lm(formula = points ~ 1 + attitude + stra + deep, data = learning2014)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -17.5239  -3.4276   0.5474   3.8220  11.5112 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  11.3915     3.4077   3.343  0.00103 ** 
## attitude      3.5254     0.5683   6.203 4.44e-09 ***
## stra          0.9621     0.5367   1.793  0.07489 .  
## deep         -0.7492     0.7507  -0.998  0.31974    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.289 on 162 degrees of freedom
## Multiple R-squared:  0.2097, Adjusted R-squared:  0.195 
## F-statistic: 14.33 on 3 and 162 DF,  p-value: 2.521e-08

According to the model summary, attitude shows a significant relationship with points in the model, meaning that attitude could be used to predict points. Together attitude, stra and deep explain 20.97% of points (this information is derived from the multiple R-squared).

Since stra and deep did not show significant relationship with points a new model is build by using the significant explanatory variable attitude only.

M2 <- lm(points ~ 1 + attitude, data = learning2014)

summary(M2)
## 
## Call:
## lm(formula = points ~ 1 + attitude, data = learning2014)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -16.9763  -3.2119   0.4339   4.1534  10.6645 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  11.6372     1.8303   6.358 1.95e-09 ***
## attitude      3.5255     0.5674   6.214 4.12e-09 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.32 on 164 degrees of freedom
## Multiple R-squared:  0.1906, Adjusted R-squared:  0.1856 
## F-statistic: 38.61 on 1 and 164 DF,  p-value: 4.119e-09

Variable attitude explains 19.06% of points and this explanatory variable remains significant.

Next we can do model validation by drawing few diagnostic plots. Let’s focus on residuals vs fitted values, normal QQ-plot and residuals vs leverage.

par(mfrow=c(1,3)) # makes the plots appear in a 1x3 window
plot(M2, which = c(1,2,5)) # 1: residuals vs fitted # 2: normal QQ-plot # 5: residuals vs leverage

Plot: residuals vs fitted

According to this plot, the fitted regression model seems to be appropriate. The residuals are spread randomly in the plot, indicating that the errors do not depend on the explanatory variable.

Plot: normal Q-Q

The plot indicates that the errors of the model are normally distributed, since most of the residuals follow linearity.

Plot: residuals vs leverage

No single observation stands out in the plot, implicating that single observations do not have unreasonably high impact on the model.



Week 3: Logistic regression

date()
## [1] "Fri Dec 10 12:44:30 2021"

1) Introduction and exploration of the data

The data explores student achievement in maths and Portuguese language at the secondary education level in two Portuguese schools. The data was downloaded from here and modified for this exercise.

# import the data 
students_poma <- read.table("./Data/student-portmath.txt", sep = "\t")

# dimensions 
dim(students_poma)
## [1] 370  51
# variable names
names(students_poma) 
##  [1] "school"     "sex"        "age"        "address"    "famsize"   
##  [6] "Pstatus"    "Medu"       "Fedu"       "Mjob"       "Fjob"      
## [11] "reason"     "guardian"   "traveltime" "studytime"  "schoolsup" 
## [16] "famsup"     "activities" "nursery"    "higher"     "internet"  
## [21] "romantic"   "famrel"     "freetime"   "goout"      "Dalc"      
## [26] "Walc"       "health"     "n"          "id.p"       "id.m"      
## [31] "failures"   "paid"       "absences"   "G1"         "G2"        
## [36] "G3"         "failures.p" "paid.p"     "absences.p" "G1.p"      
## [41] "G2.p"       "G3.p"       "failures.m" "paid.m"     "absences.m"
## [46] "G1.m"       "G2.m"       "G3.m"       "alc_use"    "high_use"  
## [51] "cid"

The data has 370 observations by 51 variables, including binary and numeric variables. Find more information about the variables here. Separate data sets for maths and Portuguese language classes were merged and at the same time a number of variables were added to the data. Variables with suffix .p are specific for performance in Portuguese language, and with suffix .m in maths. Variable alc_use is the average of Dalc and Walc and variable high_use is ‘TRUE’ if alc_use is higher than 2.

We will to study the relationship between high/low alcohol consumption and some of the variables. Let’s choose four variables for the purpose: sex, absences, failures and G3. I’m hypothesizing that high alcohol consumption leads to increased occasions of absences and failures in the classes and lower grades in the final exam (G3). Sex might also have an impact on alcohol consumption, and I’m guessing that males show more often high alcohol consumption compared to females.

Let’s explore the distributions and relationships between these four variables and high/low alcohol consumption next.

# load the libraries
library(ggplot2)
library(GGally)
library(ggpubr)

# make a new data frame including only the variables you're interested in 
my_var <- c("high_use", "sex", "failures", "absences", "G3")
poma_4var <- students_poma[,my_var]

# high/low alcohol consumption by sex
table(high_use = poma_4var$high_use, sex = poma_4var$sex)
##         sex
## high_use   F   M
##    FALSE 154 105
##    TRUE   41  70
# fraction failures by student high/low alcohol consumption
mosaicplot(table(poma_4var$failures, poma_4var$high_use), main = "Number of failures by high/low alcohol consumption", xlab = "Number of failures", ylab = "High alcohol consumption", color = T)

# plot number of absences by high/low alcohol consumption
p1 <- ggplot(poma_4var, aes(x = high_use, y = absences, fill = high_use)) + 
            geom_boxplot() + theme_minimal() + xlab("") + ylab("Absences")

# plot final grade by high/low alcohol consumption
p2 <- ggplot(poma_4var, aes(x = high_use, y = G3, fill = high_use)) +
            geom_boxplot() + theme_minimal() + xlab("") + ylab("Final grade")

# plot the box plots together
ggarrange(p1, p2, ncol = 2, common.legend = T)

High alcohol consumption is more common in males compared to females. The frequency of failures also appears greater in proportion with high alcohol consumption compared to low. The number of absences is higher more often in students who consume high amounts of alcohol compared to the students who consume low amounts. Most of the low alcohol consumption students have been absent less than five times, when for most of the high alcohol consumption student this is less than 10. Finally, low alcohol consuming students achieve more often higher grades from the final exam compared to the high alcohol consuming students. After exploring the data, the hypothesis of high alcohol consumption leading to higher number of failures and absences and eventually lower final grades seems to hold, but the significance of this relationship is yet to be studied.

2) Logistic regression

We will use logistic regression to statistically explore the relationship between high/low alcohol consumption and sex, absences, failures and G3 (final grade).

# let's first change variable 'sex' from character to factor
poma_4var$sex <- as.factor(poma_4var$sex)

# next compute the logistic regression model
M1 <- glm(high_use ~ sex + failures + absences + G3, data = poma_4var, family = "binomial")

# model summary
summary(M1)
## 
## Call:
## glm(formula = high_use ~ sex + failures + absences + G3, family = "binomial", 
##     data = poma_4var)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.1561  -0.8429  -0.5872   1.0033   2.1393  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.38733    0.51617  -2.688  0.00719 ** 
## sexM         1.00870    0.24798   4.068 4.75e-05 ***
## failures     0.50382    0.22018   2.288  0.02213 *  
## absences     0.09058    0.02322   3.901 9.56e-05 ***
## G3          -0.04671    0.03948  -1.183  0.23671    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 452.04  on 369  degrees of freedom
## Residual deviance: 405.59  on 365  degrees of freedom
## AIC: 415.59
## 
## Number of Fisher Scoring iterations: 4
# compute odds ratios and confident intervals
OR <- coef(M1) %>% exp
CI <- confint(M1) %>% exp
## Waiting for profiling to be done...
cbind(OR, CI) # prints out the ORs with their CIs
##                    OR      2.5 %    97.5 %
## (Intercept) 0.2497422 0.08880747 0.6760545
## sexM        2.7420380 1.69666006 4.4943946
## failures    1.6550376 1.08094265 2.5808643
## absences    1.0948038 1.04844539 1.1486025
## G3          0.9543647 0.88291082 1.0311936

The logistic regression model suggests that males have significantly higher probability for high alcohol consumption compared to females. Students showing high alcohol consumption are also more likely to fail in the classes and be absent from the school. These results were significant. However, high alcohol consumption is not affecting the final grade. The odds ratio for sex indicates a student showing high alcohol consumption is 2.7 times more likely to be male. The odds ratios indicate that a person is 1.65 times more likely to fail a class and 1.1 times more likely to be absent if their alcohol consumption is high.

Let’s modify the model so that it includes only the variables that showed statistically significant relationship with high/low alcohol consumption. Then we will explore the predictive power of this model.

# make a new model
M2 <- glm(high_use ~ sex + failures + absences, data = poma_4var, family = "binomial")

summary(M2)
## 
## Call:
## glm(formula = high_use ~ sex + failures + absences, family = "binomial", 
##     data = poma_4var)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.1550  -0.8430  -0.5889   1.0328   2.0374  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.94150    0.23129  -8.394  < 2e-16 ***
## sexM         0.99731    0.24725   4.034 5.49e-05 ***
## failures     0.59759    0.20698   2.887  0.00389 ** 
## absences     0.09245    0.02323   3.979 6.91e-05 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 452.04  on 369  degrees of freedom
## Residual deviance: 406.99  on 366  degrees of freedom
## AIC: 414.99
## 
## Number of Fisher Scoring iterations: 4
# predictive model
# predict the probability of high alcohol consumption
probs <- predict(M2, type = "response")

# add the predicted probabilities to your data set
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
poma_4var <- mutate(poma_4var, probability = probs)

# use the probabilities to predict high alcohol consumption
poma_4var <- mutate(poma_4var, predictions = probability > 0.5)

# print predictions vs actual values
table(high_use = poma_4var$high_use, prediction = poma_4var$prediction)
##         prediction
## high_use FALSE TRUE
##    FALSE   252    7
##    TRUE     78   33
# show the same in a plot
p3 <- ggplot(poma_4var, aes(x = high_use, y = predictions))
p3 + geom_point(position = "jitter")

# compute the proportion of inaccurately classified individuals
# define a loss function (mean prediction error)
loss_func <- function(class, prob) {
  n_wrong <- abs(class - prob) > 0.5
  mean(n_wrong)
}

# call loss_func to compute the average number of wrong predictions in the data
loss_func(class = poma_4var$high_use, prob = 0)
## [1] 0.3

The model classifies 30% of the individuals inaccurately. This inaccuracy is best seen in classifying more student to not have high alcohol consumption as compared to the true values (see the plot).


Week 4: Clustering and classification

date()
## [1] "Fri Dec 10 12:44:31 2021"

This week we will use the data set Boston provided in the R package MASS. The R documentation file for the data can be found here.

# load the data 
library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
# dimensions
dim(Boston) # 506 observations by 14 variables
## [1] 506  14
# structure
str(Boston) # a data.frame containing numerical data
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
# two of the variables are integers, let's check their unique values
unique(Boston$chas)
## [1] 0 1
unique(Boston$rad)
## [1]  1  2  3  5  4  8  6  7 24

1) Overview of the data

# load libraries
library(ggplot2)
library(GGally)

# graphical overview of the data
ggpairs(Boston, upper = list(continuous = wrap("cor", size=4)))

# summaries
summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08205   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00

Most of the variables are continuous data, except chas and rad which are integers. The variables have different distributions and only rm shows normal distribution. Variables indus and tax show bimodal distribution, with most of the values falling in the low or the high end of the scale, and less in the middle. Variables crim, zn, nox, dis, lstat and medv are more or less left-skewed whereas variables age, pratio and black are right-skewed. There is strong positive correlation between many of the variables, as between rm and medv, and between nox and age, and strong negative correlation between as between rm and lstat, and between lstat and medv.

2) Modifing the data set

# standardize the data
boston_scaled <- as.data.frame(scale(Boston))

summary(boston_scaled)
##       crim                 zn               indus              chas        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563   Min.   :-0.2723  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668   1st Qu.:-0.2723  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109   Median :-0.2723  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150   3rd Qu.:-0.2723  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202   Max.   : 3.6648  
##       nox                rm               age               dis         
##  Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331   Min.   :-1.2658  
##  1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366   1st Qu.:-0.8049  
##  Median :-0.1441   Median :-0.1084   Median : 0.3171   Median :-0.2790  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059   3rd Qu.: 0.6617  
##  Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164   Max.   : 3.9566  
##       rad               tax             ptratio            black        
##  Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047   Min.   :-3.9033  
##  1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876   1st Qu.: 0.2049  
##  Median :-0.5225   Median :-0.4642   Median : 0.2746   Median : 0.3808  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058   3rd Qu.: 0.4332  
##  Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372   Max.   : 0.4406  
##      lstat              medv        
##  Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 3.5453   Max.   : 2.9865

The data was standardized by scaling the variables, that is, the column means were subtracted from the corresponding columns and the difference divided by standard deviation. Now the values span between negative and positive, and the difference between the minimum and the maximum value is not as great. Next we will make variable crim into a categorical variable and divide the data set into a training set and a test set.

# load dplyr
library(dplyr)

# create categories out of the numerical vector and use the quantiles as break points
bins <- quantile(boston_scaled$crim)

# create categorical variable 'crime' out of 'bins'
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = T)

# replace 'crim' with the categorical variable 'crime'
boston_scaled <- dplyr::select(boston_scaled, -crim) # remove 'crim'
boston_scaled <- data.frame(boston_scaled, crime) # add 'crime'

names(boston_scaled) # check the variable names again
##  [1] "zn"      "indus"   "chas"    "nox"     "rm"      "age"     "dis"    
##  [8] "rad"     "tax"     "ptratio" "black"   "lstat"   "medv"    "crime"
# create training data set using 80% of the data
n <- nrow(boston_scaled) # number of rows in the data set
n80 <- sample(n, size = n * 0.8) # randomly choose 80% of the rows
train <- boston_scaled[n80,] # training set

# create test data set
test <- boston_scaled[-n80,] 

3) Linear discriminant analysis

We will fit a linear discriminant analysis (LDA) on the train set and use crime as the target variable. All the other variables are predictor variables in the analysis. The crime categories will be predicted from the test data set using the LDA model.

# linear discriminant analysis fit
lda.fit <- lda(crime ~ ., data = train)

# draw a biplot
# function for the biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "orange", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

# change the 'crime' classes to numeric
classes <- as.numeric(train$crime)

# draw the plot
plot(lda.fit, dimen = 2, col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 1) # add the arrows

# save the 'crime' categories from the test set and remove the variable from the set
crime_categs <- test$crime # save the crime categories into a new object
test <- dplyr::select(test, -crime) # remove variable crime 

# predict the crime categories in the test set
lda.pred <- predict(lda.fit, newdata = test)

# the results
table(correct = crime_categs, predicted = lda.pred$class)
##                  predicted
## correct           [-0.419,-0.411] (-0.411,-0.39] (-0.39,0.00739] (0.00739,9.92]
##   [-0.419,-0.411]              15              8               0              0
##   (-0.411,-0.39]                5             18               7              0
##   (-0.39,0.00739]               1              9              18              1
##   (0.00739,9.92]                0              0               0             20

The LDA model fitted using 80% of the original data set performs quite well in predicting the categories of the crime variable. The lowest and the highest crime rates best predicted, but the two categories between these rates are not as easily correctly predicted by the LDA model.

4) Clustering

# reload the Boston data set
data('Boston')

# scale the data
boston_scaled_2 <- scale(Boston)

# calculate distance between the observations
dist_eu <- dist(boston_scaled_2, method = "euclidean")

# k-means clustering
library(factoextra)
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
set.seed(12345)
fviz_nbclust(boston_scaled_2, kmeans, method = "wss") # find the optimal amount of clusters

km <- kmeans(Boston, centers = 3) # optimal number of clusters is 3
km # print the output
## K-means clustering with 3 clusters of sizes 38, 102, 366
## 
## Cluster means:
##         crim       zn     indus       chas       nox       rm      age      dis
## 1 15.2190382  0.00000 17.926842 0.02631579 0.6737105 6.065500 89.90526 1.994429
## 2 10.9105113  0.00000 18.572549 0.07843137 0.6712255 5.982265 89.91373 2.077164
## 3  0.3749927 15.71038  8.359536 0.07103825 0.5098626 6.391653 60.41339 4.460745
##        rad      tax  ptratio     black    lstat     medv
## 1 22.50000 644.7368 19.92895  57.78632 20.44868 13.12632
## 2 23.01961 668.2059 20.19510 371.80304 17.87402 17.42941
## 3  4.45082 311.2322 17.81776 383.48981 10.38866 24.93169
## 
## Clustering vector:
##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 
##   3   3   1   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   1   1   3   3   3 
## 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   2   2   2   2 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 
##   2   2   2   2   2   2   2   1   2   2   2   2   2   2   2   2   2   2   2   2 
## 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 
##   2   2   2   2   2   2   2   2   2   1   1   1   1   1   1   1   1   1   1   1 
## 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 
##   2   2   2   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   2 
## 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 
##   2   2   2   2   2   1   2   2   2   2   1   2   2   2   1   1   1   1   2   2 
## 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 
##   2   2   2   2   2   2   1   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   3   3   3   3   3   3   3 
## 501 502 503 504 505 506 
##   3   3   3   3   3   3 
## 
## Within cluster sum of squares by cluster:
## [1]  313208.7  181891.7 2573399.1
##  (between_SS / total_SS =  84.2 %)
## 
## Available components:
## 
## [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
## [6] "betweenss"    "size"         "iter"         "ifault"
# plot the clusters in a pair plot
ggpairs(Boston, mapping = aes(col = as.factor(km$cluster), alpha = 0.5),
        upper = list(continuous = wrap("cor", size = 4)))

Cluster 3 (blue points) seems to divert from the other two clusters (green and red points).


Week 5: Dimensionality and reduction techniques

date()
## [1] "Fri Dec 10 12:45:18 2021"

This week we will analyse the human data set originating from the United Nations Development Programme. The data set investigates the development of a country by focusing on the citizens and their capabilities instead of the typically used economic growth. More information can be found here and here.

Data exploration

# load the libraries
library(ggplot2)
library(GGally)
library(dplyr)
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✓ tibble  3.1.5     ✓ purrr   0.3.4
## ✓ tidyr   1.1.4     ✓ stringr 1.4.0
## ✓ readr   2.0.2     ✓ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
## x MASS::select()  masks dplyr::select()
# import the data
human <- read.table("Data/human.txt", sep = "\t")

# graphical overview of the data
ggpairs(human)

# summaries
summary(human)
##     Edu2.FM          Labo.FM          Edu.exp         Life.exp    
##  Min.   :0.1717   Min.   :0.1857   Min.   : 5.40   Min.   :49.00  
##  1st Qu.:0.7264   1st Qu.:0.5984   1st Qu.:11.25   1st Qu.:66.30  
##  Median :0.9375   Median :0.7535   Median :13.50   Median :74.20  
##  Mean   :0.8529   Mean   :0.7074   Mean   :13.18   Mean   :71.65  
##  3rd Qu.:0.9968   3rd Qu.:0.8535   3rd Qu.:15.20   3rd Qu.:77.25  
##  Max.   :1.4967   Max.   :1.0380   Max.   :20.20   Max.   :83.50  
##       GNI            Mat.mor         Ado.birth         Parli.F     
##  Min.   :   581   Min.   :   1.0   Min.   :  0.60   Min.   : 0.00  
##  1st Qu.:  4198   1st Qu.:  11.5   1st Qu.: 12.65   1st Qu.:12.40  
##  Median : 12040   Median :  49.0   Median : 33.60   Median :19.30  
##  Mean   : 17628   Mean   : 149.1   Mean   : 47.16   Mean   :20.91  
##  3rd Qu.: 24512   3rd Qu.: 190.0   3rd Qu.: 71.95   3rd Qu.:27.95  
##  Max.   :123124   Max.   :1100.0   Max.   :204.80   Max.   :57.50

Variables are explained below

  • Edu2.FM - the ratio of female and male populations with secondary education
  • Labo.FM - the ratio of labour force participation of females and males
  • Edu.exp - expected years of education
  • Life.exp - life expectancy at birth
  • GNI - gross national income per capita
  • Mat.mor - maternal mortality ratio
  • Ado.birth - adolescent birth rate
  • Parli.FM - percentage of female representation in the parliament

All variables in this modified human data set are numeric. Expected years of education (Edu.exp) is normally distributed whereas distributions of the other variables are more or less left-skewed (GNI, Mat.mor, Ado.birth, Parli.F) or right-skewed (Labo.FM, Life.exp). Notice that GNI and Mat.mor have large variance and most values are at the lower end of the scale. Edu2.FM correlates positively with Edu.exp and Life.exp, and negatively with Mat.mor and Ado.birth. Edu.exp shows strong positive correlation with Life.exp, and strong negative correlation with Mat.mor and Ado.birth. Finally, there is strong negative correlation between Life.exp Mat.mor and Ado.birth, and between Ado.birth and Mat.mor.

Principal component analysis

# PCA
pca_human <- prcomp(human)
summary(pca_human) # variability captured by the PCs
## Importance of components:
##                              PC1      PC2   PC3   PC4   PC5   PC6    PC7    PC8
## Standard deviation     1.854e+04 185.5219 25.19 11.45 3.766 1.566 0.1912 0.1591
## Proportion of Variance 9.999e-01   0.0001  0.00  0.00 0.000 0.000 0.0000 0.0000
## Cumulative Proportion  9.999e-01   1.0000  1.00  1.00 1.000 1.000 1.0000 1.0000
# PCA biplot
# create the percentages of variance for PC1 and 2
pcs1 <- summary(pca_human)
pcs1 <- round(100*pcs1$importance[2,], digits = 1)
pcs1 <- paste0(names(pcs1), " (", pcs1, "%)")
# draw the biplot
par(mar=c(5,5,5,5)) # make larger margins
biplot(pca_human, xlab = pcs1[1], ylab = pcs1[2]) # the plot
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped
abline(v = 0, lty = 2) # adds vertical dashed line at position 0 on the x axis
mtext(c("High", "Low", "Gross National Income (GNI)"), 
      side = c(3,3,3), line = c(2,2,4), adj = c(0, 1, NA), 
      col = c("red", "blue", "black")) # add text in the top margin

# standardized values
human_std <- scale(human)

# PCA on standardized values
pca_std <- prcomp(human_std)
summary(pca_std)
## Importance of components:
##                           PC1    PC2     PC3     PC4     PC5     PC6     PC7
## Standard deviation     2.0708 1.1397 0.87505 0.77886 0.66196 0.53631 0.45900
## Proportion of Variance 0.5361 0.1624 0.09571 0.07583 0.05477 0.03595 0.02634
## Cumulative Proportion  0.5361 0.6984 0.79413 0.86996 0.92473 0.96069 0.98702
##                            PC8
## Standard deviation     0.32224
## Proportion of Variance 0.01298
## Cumulative Proportion  1.00000
# PCA biplot on standardized values
# create the percentages of variance for PC1 and 2
pcs2 <- summary(pca_std)
pcs2 <- round(100*pcs2$importance[2,], digits = 1)
pcs2 <- paste0(names(pcs2), " (", pcs2, "%)")
# draw the biplot
par(mar=c(5,5,5,5))
biplot(pca_std, xlab = pcs2[1], ylab = pcs2[2])
abline(v = 0, lty = 2)
mtext(c("High maternal mortality", "and adolescent birth ratio", "High expected years of education,", "ratio of females with secondary education,", "life expectancy at birth and gross national income"), 
      side = 3, line = c(3,2,4,3,2), adj = c(1,1,0,0,0))

The PCA plot looks very different whether the values are standardized or not. In the first plot (not standardized) there is only one variable, the GNI driving the differences between countries. As we saw in the data exploration part, GNI shows high large variance, therefore PCA assumes that this variable is more important than the other variables with smaller variance. That’s why scaling the variables before PCA is a good idea and as seen in the second PCA plot (standardized), the result looks quite different. The standardized PCA plot indicates that countries differ from each other maternal mortality ratio, adolescent birth rate, expected years of education, ratio of females with secondary education, life expectancy at birth and gross national income according to PC1, which explains 53.6% of the variation between the countries. PC2 on the other hand separates the countries according to female/male ratio in labor force and female representation in the parliament. This explains 16.2% of the variation between the countries.

Multiple correspondence analysis

Let’s do a multiple correcpondence analysis using the tea data set from the R packages FactoMineR. The data set is based on a questionnaire on tea consumption collected from 300 individuals. The data set is exploring how these individuals drink their tea and how they perceive it.

# load the tea data
library(FactoMineR)
data(tea)

# structure and dimensions
dim(tea)
## [1] 300  36
str(tea)
## 'data.frame':    300 obs. of  36 variables:
##  $ breakfast       : Factor w/ 2 levels "breakfast","Not.breakfast": 1 1 2 2 1 2 1 2 1 1 ...
##  $ tea.time        : Factor w/ 2 levels "Not.tea time",..: 1 1 2 1 1 1 2 2 2 1 ...
##  $ evening         : Factor w/ 2 levels "evening","Not.evening": 2 2 1 2 1 2 2 1 2 1 ...
##  $ lunch           : Factor w/ 2 levels "lunch","Not.lunch": 2 2 2 2 2 2 2 2 2 2 ...
##  $ dinner          : Factor w/ 2 levels "dinner","Not.dinner": 2 2 1 1 2 1 2 2 2 2 ...
##  $ always          : Factor w/ 2 levels "always","Not.always": 2 2 2 2 1 2 2 2 2 2 ...
##  $ home            : Factor w/ 2 levels "home","Not.home": 1 1 1 1 1 1 1 1 1 1 ...
##  $ work            : Factor w/ 2 levels "Not.work","work": 1 1 2 1 1 1 1 1 1 1 ...
##  $ tearoom         : Factor w/ 2 levels "Not.tearoom",..: 1 1 1 1 1 1 1 1 1 2 ...
##  $ friends         : Factor w/ 2 levels "friends","Not.friends": 2 2 1 2 2 2 1 2 2 2 ...
##  $ resto           : Factor w/ 2 levels "Not.resto","resto": 1 1 2 1 1 1 1 1 1 1 ...
##  $ pub             : Factor w/ 2 levels "Not.pub","pub": 1 1 1 1 1 1 1 1 1 1 ...
##  $ Tea             : Factor w/ 3 levels "black","Earl Grey",..: 1 1 2 2 2 2 2 1 2 1 ...
##  $ How             : Factor w/ 4 levels "alone","lemon",..: 1 3 1 1 1 1 1 3 3 1 ...
##  $ sugar           : Factor w/ 2 levels "No.sugar","sugar": 2 1 1 2 1 1 1 1 1 1 ...
##  $ how             : Factor w/ 3 levels "tea bag","tea bag+unpackaged",..: 1 1 1 1 1 1 1 1 2 2 ...
##  $ where           : Factor w/ 3 levels "chain store",..: 1 1 1 1 1 1 1 1 2 2 ...
##  $ price           : Factor w/ 6 levels "p_branded","p_cheap",..: 4 6 6 6 6 3 6 6 5 5 ...
##  $ age             : int  39 45 47 23 48 21 37 36 40 37 ...
##  $ sex             : Factor w/ 2 levels "F","M": 2 1 1 2 2 2 2 1 2 2 ...
##  $ SPC             : Factor w/ 7 levels "employee","middle",..: 2 2 4 6 1 6 5 2 5 5 ...
##  $ Sport           : Factor w/ 2 levels "Not.sportsman",..: 2 2 2 1 2 2 2 2 2 1 ...
##  $ age_Q           : Factor w/ 5 levels "15-24","25-34",..: 3 4 4 1 4 1 3 3 3 3 ...
##  $ frequency       : Factor w/ 4 levels "1/day","1 to 2/week",..: 1 1 3 1 3 1 4 2 3 3 ...
##  $ escape.exoticism: Factor w/ 2 levels "escape-exoticism",..: 2 1 2 1 1 2 2 2 2 2 ...
##  $ spirituality    : Factor w/ 2 levels "Not.spirituality",..: 1 1 1 2 2 1 1 1 1 1 ...
##  $ healthy         : Factor w/ 2 levels "healthy","Not.healthy": 1 1 1 1 2 1 1 1 2 1 ...
##  $ diuretic        : Factor w/ 2 levels "diuretic","Not.diuretic": 2 1 1 2 1 2 2 2 2 1 ...
##  $ friendliness    : Factor w/ 2 levels "friendliness",..: 2 2 1 2 1 2 2 1 2 1 ...
##  $ iron.absorption : Factor w/ 2 levels "iron absorption",..: 2 2 2 2 2 2 2 2 2 2 ...
##  $ feminine        : Factor w/ 2 levels "feminine","Not.feminine": 2 2 2 2 2 2 2 1 2 2 ...
##  $ sophisticated   : Factor w/ 2 levels "Not.sophisticated",..: 1 1 1 2 1 1 1 2 2 1 ...
##  $ slimming        : Factor w/ 2 levels "No.slimming",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ exciting        : Factor w/ 2 levels "exciting","No.exciting": 2 1 2 2 2 2 2 2 2 2 ...
##  $ relaxing        : Factor w/ 2 levels "No.relaxing",..: 1 1 2 2 2 2 2 2 2 2 ...
##  $ effect.on.health: Factor w/ 2 levels "effect on health",..: 2 2 2 2 2 2 2 2 2 2 ...

All variables are factor variables (except age) and there are many (36). It was difficult to find a sensible way of visualizing this data so I jump directly into the multiple correspondence analysis part.

# multiple correspondence analysis (MCA) formula
mca_tea <- MCA(tea[,-19], graph = FALSE) # leave out variable "age" since it's not categirocal
summary(mca_tea)
## 
## Call:
## MCA(X = tea[, -19], graph = FALSE) 
## 
## 
## Eigenvalues
##                        Dim.1   Dim.2   Dim.3   Dim.4   Dim.5   Dim.6   Dim.7
## Variance               0.090   0.082   0.070   0.063   0.056   0.053   0.050
## % of var.              5.838   5.292   4.551   4.057   3.616   3.465   3.272
## Cumulative % of var.   5.838  11.130  15.681  19.738  23.354  26.819  30.091
##                        Dim.8   Dim.9  Dim.10  Dim.11  Dim.12  Dim.13  Dim.14
## Variance               0.048   0.047   0.044   0.041   0.040   0.039   0.037
## % of var.              3.090   3.053   2.834   2.643   2.623   2.531   2.388
## Cumulative % of var.  33.181  36.234  39.068  41.711  44.334  46.865  49.252
##                       Dim.15  Dim.16  Dim.17  Dim.18  Dim.19  Dim.20  Dim.21
## Variance               0.036   0.035   0.034   0.032   0.031   0.031   0.030
## % of var.              2.302   2.275   2.172   2.085   2.013   2.011   1.915
## Cumulative % of var.  51.554  53.829  56.000  58.086  60.099  62.110  64.025
##                       Dim.22  Dim.23  Dim.24  Dim.25  Dim.26  Dim.27  Dim.28
## Variance               0.028   0.027   0.026   0.025   0.025   0.024   0.024
## % of var.              1.847   1.740   1.686   1.638   1.609   1.571   1.524
## Cumulative % of var.  65.872  67.611  69.297  70.935  72.544  74.115  75.639
##                       Dim.29  Dim.30  Dim.31  Dim.32  Dim.33  Dim.34  Dim.35
## Variance               0.023   0.022   0.021   0.020   0.020   0.019   0.019
## % of var.              1.459   1.425   1.378   1.322   1.281   1.241   1.222
## Cumulative % of var.  77.099  78.523  79.901  81.223  82.504  83.745  84.967
##                       Dim.36  Dim.37  Dim.38  Dim.39  Dim.40  Dim.41  Dim.42
## Variance               0.018   0.017   0.017   0.016   0.015   0.015   0.014
## % of var.              1.152   1.092   1.072   1.019   0.993   0.950   0.924
## Cumulative % of var.  86.119  87.211  88.283  89.301  90.294  91.244  92.169
##                       Dim.43  Dim.44  Dim.45  Dim.46  Dim.47  Dim.48  Dim.49
## Variance               0.014   0.013   0.012   0.011   0.011   0.010   0.010
## % of var.              0.891   0.833   0.792   0.729   0.716   0.666   0.660
## Cumulative % of var.  93.060  93.893  94.684  95.414  96.130  96.796  97.456
##                       Dim.50  Dim.51  Dim.52  Dim.53  Dim.54
## Variance               0.009   0.009   0.008   0.007   0.006
## % of var.              0.605   0.584   0.519   0.447   0.390
## Cumulative % of var.  98.060  98.644  99.163  99.610 100.000
## 
## Individuals (the 10 first)
##                  Dim.1    ctr   cos2    Dim.2    ctr   cos2    Dim.3    ctr
## 1             | -0.580  1.246  0.174 |  0.155  0.098  0.012 |  0.052  0.013
## 2             | -0.376  0.522  0.108 |  0.293  0.350  0.066 | -0.164  0.127
## 3             |  0.083  0.026  0.004 | -0.155  0.099  0.015 |  0.122  0.071
## 4             | -0.569  1.196  0.236 | -0.273  0.304  0.054 | -0.019  0.002
## 5             | -0.145  0.078  0.020 | -0.142  0.083  0.019 |  0.002  0.000
## 6             | -0.676  1.693  0.272 | -0.284  0.330  0.048 | -0.021  0.002
## 7             | -0.191  0.135  0.027 |  0.020  0.002  0.000 |  0.141  0.095
## 8             | -0.043  0.007  0.001 |  0.108  0.047  0.009 | -0.089  0.038
## 9             | -0.027  0.003  0.000 |  0.267  0.291  0.049 |  0.341  0.553
## 10            |  0.205  0.155  0.028 |  0.366  0.546  0.089 |  0.281  0.374
##                 cos2  
## 1              0.001 |
## 2              0.021 |
## 3              0.009 |
## 4              0.000 |
## 5              0.000 |
## 6              0.000 |
## 7              0.015 |
## 8              0.006 |
## 9              0.080 |
## 10             0.052 |
## 
## Categories (the 10 first)
##                  Dim.1    ctr   cos2 v.test    Dim.2    ctr   cos2 v.test  
## breakfast     |  0.182  0.504  0.031  3.022 |  0.020  0.007  0.000  0.330 |
## Not.breakfast | -0.168  0.465  0.031 -3.022 | -0.018  0.006  0.000 -0.330 |
## Not.tea time  | -0.556  4.286  0.240 -8.468 |  0.004  0.000  0.000  0.065 |
## tea time      |  0.431  3.322  0.240  8.468 | -0.003  0.000  0.000 -0.065 |
## evening       |  0.276  0.830  0.040  3.452 | -0.409  2.006  0.087 -5.109 |
## Not.evening   | -0.144  0.434  0.040 -3.452 |  0.214  1.049  0.087  5.109 |
## lunch         |  0.601  1.678  0.062  4.306 | -0.408  0.854  0.029 -2.924 |
## Not.lunch     | -0.103  0.288  0.062 -4.306 |  0.070  0.147  0.029  2.924 |
## dinner        | -1.105  2.709  0.092 -5.240 | -0.081  0.016  0.000 -0.386 |
## Not.dinner    |  0.083  0.204  0.092  5.240 |  0.006  0.001  0.000  0.386 |
##                Dim.3    ctr   cos2 v.test  
## breakfast     -0.107  0.225  0.011 -1.784 |
## Not.breakfast  0.099  0.208  0.011  1.784 |
## Not.tea time   0.062  0.069  0.003  0.950 |
## tea time      -0.048  0.054  0.003 -0.950 |
## evening        0.344  1.653  0.062  4.301 |
## Not.evening   -0.180  0.864  0.062 -4.301 |
## lunch          0.240  0.343  0.010  1.719 |
## Not.lunch     -0.041  0.059  0.010 -1.719 |
## dinner         0.796  1.805  0.048  3.777 |
## Not.dinner    -0.060  0.136  0.048 -3.777 |
## 
## Categorical variables (eta2)
##                 Dim.1 Dim.2 Dim.3  
## breakfast     | 0.031 0.000 0.011 |
## tea.time      | 0.240 0.000 0.003 |
## evening       | 0.040 0.087 0.062 |
## lunch         | 0.062 0.029 0.010 |
## dinner        | 0.092 0.000 0.048 |
## always        | 0.056 0.035 0.007 |
## home          | 0.016 0.002 0.030 |
## work          | 0.075 0.020 0.022 |
## tearoom       | 0.321 0.019 0.031 |
## friends       | 0.186 0.061 0.030 |
# plot the results 
plot(mca_tea, invisible=c("ind"))


Week 6: Analysis of longitudinal data

date()
## [1] "Fri Dec 10 12:45:27 2021"

We will analyse longitudinal data with the help of two data sets, the RATS and the BPRS. The RATS data set investigates the effect of different diets on the body mass in 16 rats. The rats were separated into three groups, each group following a different diet, and their body mass was measured repeatedly over a 9 week period. The BPRS data set investigates suspection of schizophrenia utilizing the brief psychiatric rating scale (bprs) in 40 male subjects assigned to two treatment groups. The bprs was measured weekly over an eight week period. The above mentioned data sets are explored and analysed in separate sections below. Different analysis methods for longitudinal data will be used for the two sets.

# load libraries
library(dplyr)
library(magrittr)
## 
## Attaching package: 'magrittr'
## The following object is masked from 'package:purrr':
## 
##     set_names
## The following object is masked from 'package:tidyr':
## 
##     extract
library(ggplot2)
library(ggpubr)

The RATS: a summary measure analysis

# import the data and look at the structure
RATS_long <- read.table("Data/rats_long.txt", sep = "\t")
str(RATS_long)
## 'data.frame':    176 obs. of  5 variables:
##  $ ID    : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ Group : int  1 1 1 1 1 1 1 1 2 2 ...
##  $ wd    : chr  "WD1" "WD1" "WD1" "WD1" ...
##  $ weight: int  240 225 245 260 255 260 275 245 410 405 ...
##  $ time  : int  1 1 1 1 1 1 1 1 1 1 ...
# convert convert categorical variables to factor
RATS_long %<>% mutate_at(c("ID", "Group", "wd"), factor)

# data visualization 
p_rats <- ggplot(RATS_long, aes(x = time, y = weight, color = Group)) + 
  geom_point() + geom_smooth(se = F) +
  theme_minimal()
p_rats
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

It’s clear that rats in diet group 1 have a lower body mass than rats in diet groups 2 and 3. One of the rats in diet group 2 has greater body mass than the other rats, and while the rest of the rats in this diet group have a lower body mass than the rats in diet group 3, the one rat with greater body mass has greater mass than any rat in the diet group 3. This shifts the mean body mass in group 2 closer to the level of group 3 mean body mass. Let’s remove the outlier in diet group 2 so the groups are more comparable with each other.

# find the ID for the outlier by adding the ID numbers on the plot above
p_rats + geom_text(aes(label = ID))
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

# in each case rat number 12 is an outlier in diet group 2
# let's remove this rat from the data
RATS_long <- RATS_long[!(RATS_long$ID == "12"), ]

Let’s use the summary measure analysis to investigate the differences in weight gain between the three diet groups. For that purpose we will look at the difference in weight between the first measurement (WD1) and the last (WD64) in the three diet groups.

# make a new data set only including the first and the last measurement
RATS_comp <- RATS_long[RATS_long$wd == "WD1" | RATS_long$wd == "WD64", ]

# plot the comparisons
ggplot(RATS_comp, aes(x = Group, y = weight, col = wd)) + 
  geom_boxplot() + stat_compare_means(method = "t.test") +
  theme_minimal()

Diet 1 and 2 significantly affects the weight gain when investigating the difference in weight between the first and the last measurement. Weight gain in diet group 3 is only nearly significant.

BPRS: linear mixed effects models

# import the data and look at the structure
BPRS_long <- read.table("Data/bprs_long.txt", sep = "\t")
str(BPRS_long)
## 'data.frame':    360 obs. of  5 variables:
##  $ treatment: int  1 1 1 1 1 1 1 1 1 1 ...
##  $ subject  : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ weeks    : chr  "week0" "week0" "week0" "week0" ...
##  $ bprs     : int  42 58 54 55 72 48 71 30 41 57 ...
##  $ week     : int  0 0 0 0 0 0 0 0 0 0 ...
# convert categorical variables to factor
BPRS_long %<>% mutate_at(c("treatment", "subject", "weeks"), factor)

# data visualization
p1 <- ggplot(BPRS_long, aes(x = week, y = bprs, color = treatment)) + 
  geom_point() + geom_smooth(se = F) + theme_minimal() # scatterplot with regression line
p2 <- ggplot(BPRS_long, aes(x = treatment, y = bprs, color = treatment)) + 
  geom_boxplot(aes(color = treatment)) + theme_minimal() # boxplot 

ggarrange(p1,p2, ncol = 2)
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

Both treatments (1 and 2) help to bring down the BPRS value in the course of 8 weeks period and it seems that there is no significant difference between treatment 1 and 2. However, there is an outlier in treatment group 2 which might diminish the difference between the treatments.